<template>
  <div>
    <!-- prettier-ignore -->
    <button @click="testToken" type="button">测试获取Token</button>
    <el-upload
      ref="upload"
      multiple
      action="http://upload.qiniup.com"
      :data="TokenQiNiu"
      :before-upload="beforeUpload"
      :http-request="uploadFile"
      :on-progress="handleProgress"
      :on-success="handleUploadSuccess"
      :on-remove="handleRemove"
      list-type="picture"
      :file-list="fileUploadList">
      <el-button type="primary" icon="el-icon-plus">选择图片</el-button>
    </el-upload>
    <pre>{{ fileUploadList }}</pre>
  </div>
</template>

<script>
import * as qiniu from 'qiniu-js';
export default {
  data() {
    return {
      TokenQiNiu: {}, //
      fileUploadList: [],
      qiniuAddress: 'http://qiniuoss.chenxi618.com',
    };
  },
  computed: {},
  methods: {
    testToken() {
      this.$axios
        .get('http://ewapi.chenxi18.com:82/api/Material/GetQiNiuToken')
        .then((res) => {
          console.log(res);
        });
    },
    /* 上传图片相关 s */
    beforeUpload(file) {
      if (file.type != 'image/png' && file.type != 'image/jpeg') {
        this.$message({
          message: '请上传正确的图片',
          type: 'warning',
        });
        return false;
      }
    }, // 上传之前回调
    uploadFile(elUpload) {
      return this.$axios
        .get('http://ewapi.chenxi18.com:82/api/Material/GetQiNiuToken')
        .then((res) => {
          let token = res.data;
          let match = elUpload.file.name.match(/([^\/]+)\.(\w+)$/);
          let newFileName = `${this.$mock.mock('@uuid')}${match[1]}.${
            match[2]
          }`;

          let config = {
            useCdnDomain: true, //是否使用七牛的CDN加速域名上传，默认为false，上传后获取的文件地址为七牛存储空间的原始URL。
            region: qiniu.region.z0, //指定文件上传的区域，例如z0:华东,z1:华北,z2:华南,na0:北美。
          };
          let putExtra = {
            fname: newFileName, //用于指定上传的文件名，如果不指定，则默认使用上传文件的原始文件名。
            params: {}, //用于指定上传文件的扩展参数，例如文件类型、文件大小、上传时间等。
          };
          let key = newFileName;
          let observable = qiniu.upload(
            elUpload.file,
            key,
            token,
            putExtra,
            config
          );
          return new Promise((resolve, reject) => {
            observable.subscribe({
              next(res) {
                // console.log(res);
              },
              error(err) {
                reject(err);
              },
              complete(res) {
                resolve(res);
              },
            });
          });
        });
    },
    handleProgress(event, file, fileList) {
      console.log(94);
      console.table(fileList);
    },
    handleUploadSuccess(response, file, fileList) {
      console.log(98);
      this.fileUploadList = fileList;
      console.log(this.fileUploadList);

      // 如果只使用控件原生上传只会返回{hash:hash,key:hash}
      // 必须使用qiniu创建 监听对象 observable，通过key或putExtra.fname配置新文件名才能获得{hash:hash,key:key/putExtra.fname}
      // this.fileUploadList.splice(0, this.fileUploadList.length);
      // fileList.forEach((v, i, a) => {
      //   v.url = `${this.qiniuAddress}/${v.response.key}`;
      //   this.fileUploadList.push(v);
      // });
    }, // 上传成功
    uploadError() {
      this.$message.error(`图片上传失败`);
      return;
    },
    handleRemove(file, fileList) {
      this.fileUploadList = fileList;
    },

    /* e 上传图片相关 */
    uploadFun() {
      return {
        handlePreview(file) {}, // :on-preview;点击文件列表中已上传的文件时的钩子
        handleRemove(file, fileList) {}, // :on-remove;文件列表移除文件时的钩子
        handleSuccess(response, file, fileList) {}, // :on-success;文件上传成功时的钩子
        handleError(err, file, fileList) {}, // :on-error;文件上传失败时的钩子
        handleProgress(event, file, fileList) {}, // :on-progress;文件上传时的钩子
        handleChange(file, fileList) {}, // :on-change	文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
        handleBeforeUpload(file) {}, // :before-upload;上传文件之前的钩子，
        handleBeforeRemove(file, fileList) {}, // :before-remove;删除文件之前的钩子,
        handleUpload(elupload) {}, //:http-request;覆盖默认的上传行为，
        handleExceed(files, fileList) {}, // :on-exceed;文件超出个数限制时的钩子
      };
    },
  },
};
</script>

<style>
</style>